package cn.wubo.dynamic.schedule;

import cn.wubo.dynamic.schedule.entity.TaskRecord;
import cn.wubo.dynamic.schedule.service.TaskService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
public class InitTask implements ApplicationRunner {

    @Resource
    TaskService taskService;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        // 检查表结构
        taskService.checkTable();
        // 获取任务记录列表
        List<TaskRecord> list = taskService.list();
        // 启动时加载任务
        list.stream().filter(taskRecord -> "1".equals(taskRecord.getIsStartCron())).forEach(taskRecord -> {
            try {
                taskService.start(taskRecord.getId());
            } catch (Exception e) {
                // 记录错误日志
                log.error(e.getMessage(), e);
            }
        });
        // 启动时执行
        list.stream().filter(taskRecord -> "1".equals(taskRecord.getIsStartRun())).forEach(taskRecord -> {
            try {
                taskService.runOnce(taskRecord.getId());
            } catch (Exception e) {
                // 记录错误日志
                log.error(e.getMessage(), e);
            }
        });
    }

}
